<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >

      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="合同类型" prop="contractType">
        <el-select
          v-model="queryParams.contractType"
          placeholder="请选择"
          clearable
          style="width: 200px"
        >
          <el-option label="租赁" :value="1"> </el-option>
          <el-option label="买卖" :value="2"> </el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="交易类型" prop="buyType">
        <el-select
          v-model="queryParams.buyType"
          placeholder="请选择"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in transactionTypeList"
            :key="item.id"
            :label="item.businessName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业主姓名" prop="ownerName">
        <el-input
            v-model="queryParams.ownerName"
            placeholder="请输入业主姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="签约时间">
        <el-date-picker
            v-model="rangeDate"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:contract:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:contract:importData']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            v-hasPermi="['system:bill:export']"
            plain
            @click="handleExport"
        >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="房源地址" align="center" prop="propertyAddress" />
      <el-table-column
        label="合同类型"
        align="center"
        prop="contractTypeName"
      />

      <el-table-column label="签约人" align="center" prop="signerName" />

      <el-table-column label="签约日期" align="center" sortable prop="signDate">
      </el-table-column>
      <el-table-column label="业主" align="center" prop="ownerName" />
      <el-table-column label="客户" align="center" prop="customerName" />
      <el-table-column label="合同总收" align="center" prop="totalAmount">
        <template #default="scope">
          <span>{{
            scope.row.totalAmount ? `${scope.row.totalAmount}元` : `0元`
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="buyTypeName">
        <template #default="scope">
          <el-tag type="primary"> {{ scope.row.buyTypeName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        sortable
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:contract:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:contract:remove']"
            >删除</el-button
          >
          <!-- 成本管理 -->
          <el-button
            link
            type="primary"
            @click="handleCost(scope.row)"
            v-hasPermi="['system:contract:edit']"
            >成本管理</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <div class="contract-container">
        <div class="contract-title">房屋买卖合同信息</div>
        <el-form
          ref="postRef"
          :model="form"
          label-width="120px"
          label-position="left"
          :rules="rules"
        >
          <!-- 合同类型 -->
          <el-form-item label="合同类型" prop="contractType">
            <div class="checkbox-row">
              <el-radio-group v-model="form.contractType">
                <el-radio :value="2">买卖</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <!-- 交易类型 -->
          <el-form-item label="交易类型" prop="buyType">
            <div class="checkbox-row">
              <el-radio-group v-model="form.buyType">
                <el-radio
                  v-for="item in transactionTypeList"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.businessName }}</el-radio
                >
              </el-radio-group>
            </div>
          </el-form-item>

          <!-- 房屋位置信息 -->
          <el-form-item label="房屋位置" prop="propertyObject.provinceName">
            <el-select
              v-model="form.propertyObject.provinceName"
              placeholder="省"
              style="width: 12%; margin-right: 6px"
              @change="selectSheng"
            >
              <el-option
                v-for="item in shengList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>

            <el-select
              v-model="form.propertyObject.cityName"
              placeholder="市"
              style="width: 12%; margin-right: 6px"
              @change="selectCity"
            >
              <el-option
                v-for="item in cityList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="form.propertyObject.districtName"
              placeholder="区"
              style="width: 12%; margin-right: 6px"
            >
              <el-option
                v-for="item in quList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
            <el-input
              v-model="form.propertyObject.villageName"
              placeholder="小区"
              style="width: 18%; margin-right: 6px"
              @blur="validateHouseAddressField"
            />
            <el-input
              v-model="form.propertyObject.floorName"
              placeholder="楼栋"
              style="width: 12%; margin-right: 6px"
              @blur="validateHouseAddressField"
            />
            <el-input
              v-model="form.propertyObject.elementName"
              placeholder="单元"
              style="width: 12%; margin-right: 6px"
              @blur="validateHouseAddressField"
            />
            <el-input
              v-model="form.propertyObject.roomName"
              placeholder="房间号"
              style="width: 12%"
              @blur="validateHouseAddressField"
            />
          </el-form-item>
          <el-form-item label="签约人" prop="signerName" v-if="form.signerName">
            <el-input
              v-model="form.signerName"
              readonly
              placeholder="请输入签约人姓名"
            ></el-input>
          </el-form-item>
          <!-- 签约信息 -->
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="签约时间" prop="signDate">
                <el-date-picker
                  v-model="form.signDate"
                  type="date"
                  placeholder="请选择签约时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出售总价" prop="totalAmount">
                <el-input v-model="form.totalAmount" placeholder="出售总价">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 卖方信息 -->
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="卖方" prop="ownerName">
                <el-input v-model="form.ownerName" placeholder="姓名"
              /></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="ownerIdCard">
                <el-input
                  v-model="form.ownerIdCard"
                  placeholder="身份证号"
                  maxlength="18"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="ownerPhone">
                <el-input
                  v-model="form.ownerPhone"
                  placeholder="电话"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 共有人 -->
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="共有人" prop="ownerCommonName">
                <el-input v-model="form.ownerCommonName" placeholder="姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="ownerCommonIdCard">
                <el-input
                  v-model="form.ownerCommonIdCard"
                  placeholder="身份证号"
                  maxlength="18"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="ownerCommonPhone">
                <el-input
                  v-model="form.ownerCommonPhone"
                  placeholder="电话"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 买方信息 -->
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="买方" prop="customerName">
                <el-input v-model="form.customerName" placeholder="姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="customerIdCard">
                <el-input
                  v-model="form.customerIdCard"
                  placeholder="身份证号"
                  maxlength="18"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="customerPhone">
                <el-input
                  v-model="form.customerPhone"
                  placeholder="电话"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 共同购买人 -->
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="共同购买人" prop="togetherBuyName">
                <el-input v-model="form.togetherBuyName" placeholder="姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="togetherBuyIdCard">
                <el-input
                  v-model="form.togetherBuyIdCard"
                  placeholder="身份证号"
                  maxlength="18"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="togetherBuyPhone">
                <el-input
                  v-model="form.togetherBuyPhone"
                  placeholder="电话"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 金额项 -->
          <el-form-item label="定金" prop="depositPrice">
            <el-input
              v-model="form.depositPrice"
              placeholder="定金"
              style="width: 20%"
              @blur="caLetter('depositPriceCapital', form.depositPrice)"
            >
              <template #append>元</template>
            </el-input>
            <el-input
              v-model="form.depositPriceCapital"
              readonly
              placeholder="大写金额"
              style="width: 60%; margin-left: 10px"
            />
          </el-form-item>
          <el-form-item label="履约保证金">
            <el-input
              v-model="form.bondPrice"
              placeholder="保证金"
              style="width: 20%"
              @blur="caLetter('bondPriceCapital', form.bondPrice)"
            >
              <template #append>元</template>
            </el-input>
            <el-input
              v-model="form.bondPriceCapital"
              placeholder="大写金额"
              readonly
              style="width: 60%; margin-left: 10px"
            />
          </el-form-item>
          <el-form-item label="物业保证金">
            <el-input
              v-model="form.propertyPrice"
              placeholder="保证金"
              style="width: 20%"
              @blur="caLetter('propertyPriceCapital', form.propertyPrice)"
            >
              <template #append>元</template>
            </el-input>
            <el-input
              v-model="form.propertyPriceCapital"
              placeholder="大写金额"
              readonly
              style="width: 60%; margin-left: 10px"
            />
          </el-form-item>

          <!-- 区域 -->
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="区域" prop="regionId">
                <el-select
                  v-model="form.regionId"
                  filterable
                  clearable
                  placeholder="区域"
                  @change="selectRegin"
                >
                  <el-option
                    v-for="item in companyList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="storeId">
                <el-select
                  v-model="form.storeId"
                  filterable
                  clearable
                  placeholder="门店"
                  @change="selectStore"
                >
                  <el-option
                    v-for="item in storeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="brokerUserId">
                <el-select
                  v-model="form.brokerUserId"
                  filterable
                  clearable
                  placeholder="经纪人"
                >
                  <el-option
                    v-for="item in agentList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="subLoad" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <!-- <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div> -->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="subLoad" @click="submitFileForm"
            >确 定</el-button
          >
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ContractList">
import { getToken } from "@/utils/auth";
import {
  listContract,
  listAllTransaction,
  addContract,
  getCalLetter,
  queryContract,
  editContract,
  delContract,
  getRegionList,
} from "@/api/contract/contractList";
import { ref } from "vue";
import { listCompany, listStore, listWorker } from "@/api/business/tcForm";
import { reactive } from "vue";
import router from "@/router";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const subLoad = ref(false);
const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: undefined,
    contractType: null,
    buyType: null,
  },
});

// 房屋地址验证函数
const validateHouseAddress = (rule, value, callback) => {
  const propertyObject = form.value.propertyObject || {};

  if (!propertyObject.provinceName) {
    return callback(new Error("请选择省份"));
  }
  if (!propertyObject.cityName) {
    return callback(new Error("请选择市"));
  }
  if (!propertyObject.districtName) {
    return callback(new Error("请选择区"));
  }
  if (!propertyObject.villageName) {
    return callback(new Error("请输入小区"));
  }
  if (!propertyObject.floorName) {
    return callback(new Error("请输入楼栋"));
  }
  if (!propertyObject.elementName) {
    return callback(new Error("请输入单元"));
  }
  if (!propertyObject.roomName) {
    return callback(new Error("请输入房间号"));
  }

  callback();
};

// 触发房屋地址验证的函数
const validateHouseAddressField = () => {
  proxy.$refs["postRef"].validateField("propertyObject.provinceName");
};

const rules = reactive({
  contractType: [
    { required: true, message: "请选择合同类型", trigger: "change" },
  ],
  buyType: [{ required: true, message: "请选择交易类型", trigger: "change" }],
  // 房屋位置
  "propertyObject.provinceName": [
    { required: true, validator: validateHouseAddress, trigger: "change" },
  ],

  signDate: [{ required: true, message: "请选择签约时间", trigger: "change" }],
  totalAmount: [
    { required: true, message: "请输入出售总价", trigger: "blur" },
    {
      pattern: /^\d+(\.\d+)?$/,
      message: "请输入合法的金额",
      trigger: "blur",
    },
  ],
  ownerName: [{ required: true, message: "请输入卖方姓名", trigger: "blur" }],
  ownerIdCard: [
    { required: true, message: "请输入卖方身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "身份证格式不正确",
      trigger: "blur",
    },
  ],
  ownerPhone: [
    { required: true, message: "请输入卖方联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  //共有人
  ownerCommonIdCard: [
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "身份证格式不正确",
      trigger: "blur",
    },
  ],
  ownerCommonPhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  customerName: [
    { required: true, message: "请输入买方姓名", trigger: "blur" },
  ],
  customerIdCard: [
    { required: true, message: "请输入买方身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "身份证格式不正确",
      trigger: "blur",
    },
  ],
  customerPhone: [
    { required: true, message: "请输入买方联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  //共同购买人
  togetherBuyIdCard: [
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "身份证格式不正确",
      trigger: "blur",
    },
  ],
  togetherBuyPhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],

  regionId: [{ required: true, message: "请选择区域", trigger: "change" }],
  storeId: [{ required: true, message: "请选择门店", trigger: "change" }],
  brokerUserId: [
    { required: true, message: "请选择经纪人", trigger: "change" },
  ],
});
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
      "/system/bill/export",
      {
        ...queryParams.value,
      },
      `bill_${new Date().getTime()}.xlsx`
  );
}
// 自定义唯一性校验函数
function validateUniqueRoles() {
  const names = new Set();
  const idCards = new Set();
  const phones = new Set();

  let nameRepeated = false;
  let idCardRepeated = false;
  let phoneRepeated = false;

  const values = [
    {
      name: form.value.ownerName?.trim(),
      idCard: form.value.ownerIdCard?.trim(),
      phone: form.value.ownerPhone?.trim(),
    },
    {
      name: form.value.ownerCommonName?.trim(),
      idCard: form.value.ownerCommonIdCard?.trim(),
      phone: form.value.ownerCommonPhone?.trim(),
    },
    {
      name: form.value.customerName?.trim(),
      idCard: form.value.customerIdCard?.trim(),
      phone: form.value.customerPhone?.trim(),
    },
    {
      name: form.value.togetherBuyName?.trim(),
      idCard: form.value.togetherBuyIdCard?.trim(),
      phone: form.value.togetherBuyPhone?.trim(),
    },
  ];

  for (const item of values) {
    if (item.name) {
      if (names.has(item.name)) {
        nameRepeated = true;
      } else {
        names.add(item.name);
      }
    }

    if (item.idCard) {
      if (idCards.has(item.idCard)) {
        idCardRepeated = true;
      } else {
        idCards.add(item.idCard);
      }
    }

    if (item.phone) {
      if (phones.has(item.phone)) {
        phoneRepeated = true;
      } else {
        phones.add(item.phone);
      }
    }
  }

  // if (nameRepeated) {
  //   throw new Error("姓名重复");
  // }

  if (idCardRepeated) {
    throw new Error("身份证号不能重复");
  }

  if (phoneRepeated) {
    throw new Error("手机号不能重复");
  }

  return true;
}
//成本管理
function handleCost(row) {
  router.push({
    path: "/business/costManager",
    query: { contractNo: row.contractNo },
  });
}
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/contract/importData",
});
const { queryParams, form } = toRefs(data);

//区域门店经纪人
const companyList = ref([]);
function getAreaList() {
  listCompany().then((res) => {
    companyList.value = res.data;
  });
}
getAreaList();
const storeList = ref([]);
function selectRegin(val) {
  listStore({ regionId: val }).then((res) => {
    storeList.value = res.data;
    form.value.storeId = "";
    form.value.brokerUserId = "";
  });
}
const agentList = ref([]);
function selectStore(val) {
  listWorker({ storeId: val }).then((res) => {
    agentList.value = res.data;
    form.value.brokerUserId = "";
  });
}

//省市区
const shengList = ref([]);
const cityList = ref([]);
const quList = ref([]);
async function getRegin(level, parentId) {
  return new Promise((resolve, reject) => {
    getRegionList({ level, parentId }).then((res) => {
      if (level == 1) {
        shengList.value = res.data;
        resolve(shengList);
      } else if (level == 2) {
        cityList.value = res.data;
        resolve(cityList);
      } else {
        quList.value = res.data;
        resolve(quList);
      }
    });
  });
}
async function selectSheng(val, type = 1) {
  const parent = shengList.value.find((sheng) => sheng.name === val);
  if (type == 1) {
    form.value.propertyObject.cityName = "";
    form.value.propertyObject.districtName = "";
  }

  const cityList = await getRegin(2, parent.id);
  return cityList;
}

async function selectCity(val, type = 1) {
  const parent = cityList.value.find((city) => city.name === val);
  if (type == 1) {
    form.value.propertyObject.districtName = "";
  }
  const quList = await getRegin(3, parent.id);
  return quList;
}
getRegin(1);

// 交易类型列表
const transactionTypeList = ref([]);
function gettracList() {
  listAllTransaction().then((res) => {
    transactionTypeList.value = res.data;
  });
}
gettracList();

//获取大写金额接口
function caLetter(key, amount) {
  if (amount) {
    getCalLetter({ amount }).then((res) => {
      form.value[key] = res.msg;
    });
  } else {
    form.value[key] = "";
  }
}

/** 查询岗位列表 */
function getList() {
  loading.value = true;
  listContract(queryParams.value).then((response) => {
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    propertyObject: {},
    contractType: 2,
  };
  proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  queryContract(id).then(async (response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改";
    await selectSheng(form.value.propertyObject.provinceName, 2);
    console.log(form.value.propertyObject);
    await selectCity(form.value.propertyObject.cityName, 2);
    listStore({ regionId: form.value.regionId }).then((res) => {
      storeList.value = res.data;
    });
    listWorker({ storeId: form.value.storeId }).then((res) => {
      agentList.value = res.data;
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      try {
        // Step 2: 再校验唯一性（自定义）
        validateUniqueRoles();
        subLoad.value = true;
        if (form.value.id != undefined) {
          editContract(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              subLoad.value = false;
              open.value = false;
              getList();
            })
            .catch((err) => {
              subLoad.value = false;
            });
        } else {
          addContract(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("新增成功");
              subLoad.value = false;
              open.value = false;
              getList();
            })
            .catch((err) => {
              subLoad.value = false;
            });
        }
      } catch (err) {
        if (err instanceof Error) {
          proxy.$modal.msgError(err.message);
        } else {
          proxy.$modal.msgError("请检查表单填写");
        }
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(function () {
      return delContract(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "common/downloadContractTemplate",
    {},
    `contract_template_${new Date().getTime()}.xlsx`
  );
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  subLoad.value = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  subLoad.value = true;
  proxy.$refs["uploadRef"].submit();
}

getList();
</script>
<style scoped lang="scss">
.contract-container {
  border: 1px solid #dcdfe6;
  padding: 20px;
  font-family: "Microsoft YaHei", sans-serif;
  background-color: #fff;
  .el-form-item {
    margin-bottom: 18px;
    display: flex;
    align-items: center;
  }
}
.contract-title {
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
  font-size: 16px;
}

.checkbox-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
</style>
